package eu.webmedia.recruitment;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

import org.mortbay.jetty.Connector;
import org.mortbay.jetty.Handler;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.nio.SelectChannelConnector;
import org.mortbay.jetty.webapp.WebAppContext;
import org.mortbay.xml.XmlConfiguration;

public class StartJetty {
	
	private static Server server;

	public static void main(String[] args) throws Exception {
		String jettyPort = args[0];
		String monitorPort = args[1];
		
		server = new Server();

		Connector connector = new SelectChannelConnector();
		connector.setPort(Integer.parseInt(jettyPort));
		connector.setMaxIdleTime(30000);
		server.setConnectors(new Connector[] { connector });
		server.setStopAtShutdown(true);

		WebAppContext webapp = new WebAppContext();
		webapp.setContextPath("/");
		webapp.setWar("war");
		server.setHandlers(new Handler[] { webapp });

		XmlConfiguration configuration = new XmlConfiguration(new FileInputStream("jetty/jettyEnv.xml"));
		configuration.configure(webapp);
		
		Thread monitor = new MonitorThread(Integer.parseInt(monitorPort));
        monitor.start();
        
		server.start();
		server.join();
	}

	private static class MonitorThread extends Thread {

		private ServerSocket socket;

		public MonitorThread(int monitorPort) {
			setDaemon(true);
			setName("StopMonitor");
			try {
				socket = new ServerSocket(monitorPort, 
						1, InetAddress.getByName("127.0.0.1"));
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		}

		@Override
		public void run() {
			Socket accept;
			try {
				accept = socket.accept();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(accept.getInputStream()));
				reader.readLine();
				System.out.println("*** stopping jetty embedded server");
				server.stop();
				accept.close();
				socket.close();
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		}
	}

}
